import { defineAsyncComponent, AsyncComponentLoader, Component } from 'vue'
// @ts-ignore - ckeditor 不支持 ts
import CKEditor from '@ckeditor/ckeditor5-vue'

export const SUPPORT_LANGUAGES = [
  'zh-cn',
  'en'
]
export const DEFAULT_LANGUAGE = 'zh-cn'

export function getLanguage(language: string): string {
  return language && SUPPORT_LANGUAGES.includes(language) ? language : DEFAULT_LANGUAGE
}

// 加载语言包
function loadLanguageFile(language: string): Promise<any> {
  return new Promise((resolve => {
    const script = document.createElement('script')
    // 语言包路径
    let filePath = `${process.env.BASE_URL}/${process.env.VUE_APP_LANGUAGET_FILE_PATH}/${language}.js`
    // 处理多余的 /
    filePath = filePath.replace(/\/+/g, '/')

    script.src = filePath
    script.onload = resolve
    document.head.appendChild(script)
  }))
}

type ckeditorComponent = Component | AsyncComponentLoader

/*
* 语言初始化
* 切换语言时，ckeditor 需要在组件加载之前加载完成语言包，否则设置语言会无效
* 因此当需要加载语言包时，将 ckeditor 包装为异步组件，以确保在组件加载之前 语言包加载完成
* */
export default function languageInit(language: string): ckeditorComponent {
  // 配置语言 在 支持语言列表中 且 不是默认语言 才需要加载语言包
  const needLoadLanguageFile = language !== DEFAULT_LANGUAGE

  return needLoadLanguageFile
    ? defineAsyncComponent(
      () => loadLanguageFile(language).then(() => CKEditor.component)
    )
    : CKEditor.component
}
